package com.yangtzeu.jwc.fragment;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Map;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.yangtzeu.jwc.activity.LoginActivity;
import com.yangtzeu.jwc.activity.MainActivity;
import com.yangtzeu.jwc.activity.NewsActivity;
import com.yangtzeu.jwc.activity.TimetableActivity;
import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.business.NewsListParser;
import com.yangtzeu.jwc.business.BaseParser.ParserListener;
import com.yangtzeu.jwc.business.NewsParser;
import com.yangtzeu.jwc.businessservice.BusinessHttpCallBack;
import com.yangtzeu.jwc.businessservice.impl.JwcServiceImpl;
import com.yangtzeu.jwc.businessservice.impl.StudentServiceImpl;
import com.yangtzeu.jwc.customview.CustomeProgressDialog;
import com.yangtzeu.jwc.domain.Kb;
import com.yangtzeu.jwc.domain.KbSelection;
import com.yangtzeu.jwc.domain.Student;
import com.yangtzeu.jwc.utils.G;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.T;

@SuppressLint("HandlerLeak")
public class TimetableFragment extends Fragment {
    private MyHandler myHandler;
    private ProgressDialog dialog;
    private KbSelection kbSelection;
    private Button bt_year;
    private Button bt_term;
    private Button bt_dept;
    private Button bt_class;
    private Button bt_queryKebiao;
    private Button bt_refresh_kbslction;
    private Button queryMyKebiao;
    private Button xiaoli;
    private TextView queryMyKbTips;
    private Map<String, String> currentClass;
    String[][] timetable;

    private static final int SHOWPROGRESSDIALOG = 0;
    private static final int DISMISSDIALOG = 1;
    private static final int LOADINGFAILED = 2;
    private static final int LOADINGSELECTIONFINISHED = 3;
    private static final int LOADIINGCLASSFINISHED = 4;
    private static final int LOADINGTIMETABLEFINISHED = 5;

    NewsListParser xlcxParser = new NewsListParser(G.XLCX, "校历查询");

    private class MyHandler extends Handler {
	@Override
	public void handleMessage(Message msg) {
	    switch (msg.what) {
	    case SHOWPROGRESSDIALOG:
		String dialogMsg = msg.getData().getString("msg");
		dialog = CustomeProgressDialog.show(getActivity(), dialogMsg);
		break;
	    case DISMISSDIALOG:
		if (dialog != null) {
		    dialog.dismiss();
		}
		break;
	    case LOADINGFAILED:
		myHandler.sendEmptyMessage(DISMISSDIALOG);
		String failureMsg = msg.getData().getString("msg");
		MyApplication.getInstance().showShortToast(failureMsg);
		break;
	    case LOADINGSELECTIONFINISHED:
		myHandler.sendEmptyMessage(DISMISSDIALOG);
		go();
		break;
	    case LOADIINGCLASSFINISHED:
		myHandler.sendEmptyMessage(DISMISSDIALOG);
		kbSelection.setClasses(currentClass);
		if (currentClass.size() != 0) {
		    bt_class.setText(map2Array(currentClass)[0]);
		} else {
		    bt_class.setText("");
		}
		break;
	    case LOADINGTIMETABLEFINISHED:
		myHandler.sendEmptyMessage(DISMISSDIALOG);
		Intent intent = new Intent();
		intent.setClass(getActivity(), TimetableActivity.class);
		intent.putExtra("timetable", new Kb(timetable));
		startActivity(intent);
		break;
	    }
	}
    }

    // 初始化几个选择器
    private void go() {
	if (kbSelection.getYears().size() != 0) {
	    bt_year.setText(kbSelection.getSelectedYear());
	}
	if (kbSelection.getTerms().size() != 0) {
	    bt_term.setText(kbSelection.getSelectedTerm());
	}
	if (kbSelection.getDepts().size() != 0)
	    bt_dept.setText(map2Array(kbSelection.getDepts())[0]);
	if (kbSelection.getClasses().size() != 0)
	    bt_class.setText(map2Array(kbSelection.getClasses())[0]);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onActivityCreated(savedInstanceState);
	bt_year = (Button) getActivity().findViewById(R.id.bt_year);
	bt_term = (Button) getActivity().findViewById(R.id.bt_term);
	bt_dept = (Button) getActivity().findViewById(R.id.bt_dept);
	bt_class = (Button) getActivity().findViewById(R.id.bt_class);
	bt_queryKebiao = (Button) getActivity().findViewById(R.id.queryKebiao);
	bt_refresh_kbslction = (Button) getActivity().findViewById(R.id.bt_refresh_kbslction);
	queryMyKebiao = (Button) getActivity().findViewById(R.id.queryMyKebiao);
	queryMyKbTips = (TextView) getActivity().findViewById(R.id.queryMyKbTips);
	xiaoli = (Button) getActivity().findViewById(R.id.queryXiaoli);
	OnButtonClickListener listener = new OnButtonClickListener();
	bt_year.setOnClickListener(listener);
	bt_term.setOnClickListener(listener);
	bt_dept.setOnClickListener(listener);
	bt_class.setOnClickListener(listener);
	bt_queryKebiao.setOnClickListener(listener);
	bt_queryKebiao.setOnClickListener(listener);
	bt_refresh_kbslction.setOnClickListener(listener);
	queryMyKebiao.setOnClickListener(listener);
	xiaoli.setOnClickListener(listener);
	myHandler = new MyHandler();

	getSelection();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	return inflater.inflate(R.layout.timetable_fragment, container, false);
    }

    /**
     * map的key转String[]数组
     * 
     * @param mp
     * @return
     */
    public String[] map2Array(Map<String, String> mp) {
	String[] ss = new String[mp.size()];
	return mp.keySet().toArray(ss);
    }

    private final class OnButtonClickListener implements android.view.View.OnClickListener {

	@Override
	public void onClick(View view) {
	    if (view.getId() == R.id.bt_refresh_kbslction) {
		getSelection();
		return;
	    } else if (view.getId() == R.id.queryXiaoli) {
		getXiaoliList();
		return;
	    }
	    if (kbSelection == null)
		return;
	    // 点击按钮对应的集合是谁
	    Map<String, String> who = null;
	    Button button = (Button) view;
	    switch (view.getId()) {
	    case R.id.bt_year:
		who = kbSelection.getYears();
		new AlertDialog.Builder(getActivity(), R.style.draw_dialog).setTitle("选择年份").setItems(map2Array(who), new onSelectionItemClick(who, button)).show();
		break;
	    case R.id.bt_term:
		who = kbSelection.getTerms();
		new AlertDialog.Builder(getActivity(), R.style.draw_dialog).setTitle("选择学期").setItems(map2Array(who), new onSelectionItemClick(who, button)).show();
		break;
	    case R.id.bt_dept:
		who = kbSelection.getDepts();
		new AlertDialog.Builder(getActivity(), R.style.draw_dialog).setTitle("选择院系").setItems(map2Array(who), new onSelectionItemClick(who, button)).show();
		break;
	    case R.id.bt_class:
		who = kbSelection.getClasses();
		new AlertDialog.Builder(getActivity(), R.style.draw_dialog).setTitle("选择班级").setItems(map2Array(who), new onSelectionItemClick(who, button)).show();
		break;
	    case R.id.queryKebiao:
		if (kbSelection != null) {
		    getTimeTable();
		} else {
		    Toast.makeText(getActivity(), "没有查询条件!", Toast.LENGTH_LONG).show();
		}
		break;
	    case R.id.queryMyKebiao:
		if (MainActivity.student == null) {

		} else {

		}
		break;
	    default:
		break;
	    }

	}

    }

    private void getXiaoliList() {// 获取校历
	Message msg = myHandler.obtainMessage();
	msg.what = SHOWPROGRESSDIALOG;
	msg.getData().putString("msg", "请稍候...");
	myHandler.sendMessage(msg);

	new Thread(new Runnable() {
	    @Override
	    public void run() {
		// TODO Auto-generated method stub
		xlcxParser.startParse(new ParserListener() {
		    @Override
		    public void finish() {
			getXiaoli();
		    }

		    @Override
		    public void failed() {
			// TODO Auto-generated method stub
			Message m = myHandler.obtainMessage(LOADINGFAILED);
			Bundle data = new Bundle();
			data.putString("msg", "校历获取失败了");
			m.setData(data);
			myHandler.sendMessage(m);
		    }
		}, false);
	    }
	}).start();

    }

    private void getXiaoli() {
	final NewsParser parser = xlcxParser.newses.get(xlcxParser.newses.size() - 1);

	if (!parser.path.startsWith("http://jwc")) {
	    Intent intent = new Intent();
	    intent.setAction("android.intent.action.VIEW");
	    Uri content_url = Uri.parse(parser.path);
	    intent.setData(content_url);
	    startActivity(intent);
	    return;
	}
	try {
	    Document doc = Jsoup.parse(new URL(parser.path), 10000);
	    Intent intent = new Intent();
	    intent.putExtra("title", parser.title);
	    intent.putExtra("content", parser.tableCss+doc.select("#arc_word").toString());
	    intent.setClass(getActivity(), NewsActivity.class);
	    startActivity(intent);
	} catch (Exception e) {
	    Looper.prepare();
	    T.showShort(getActivity(), "网络不给力啊！");
	    e.printStackTrace();
	}
	myHandler.sendEmptyMessage(DISMISSDIALOG);
    }

    private void autoLogin() {
	Student savedStudent = StudentServiceImpl.getInstance().getSavedStudent(getActivity());
	if (savedStudent == null) {
	    showLoginWindow();
	    return;
	}
	Message msg = myHandler.obtainMessage(G.SHOWPROGRESSDIALOG);
	msg.getData().putString("msg", "正在登陆。。");
	myHandler.sendMessage(msg);
	StudentServiceImpl.getInstance().login(savedStudent.getSno(), savedStudent.getSpassword(), "1", new BusinessHttpCallBack() {
	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
		T.showLong(getActivity(), "自动登陆失败，请手动登陆！");
		showLoginWindow();
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
		myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
		if (!showUserClass()) {
		    T.showLong(getActivity(), "自动获取用户班级失败，请手动查询课表！");
		}
	    }

	});
    }

    String queryMeText = "* @ # $";

    private boolean showUserClass() {
	if (MainActivity.student != null) {
	    String tStr = queryMeText.replace("@", MainActivity.student.getSclass()).replace("#", bt_year.getText().toString()).replace("$", bt_term.getText().toString());

	    queryMyKbTips.setText(tStr);
	    queryMyKbTips.setVisibility(View.VISIBLE);
	    return true;
	} else {
	    return false;
	}
    }

    private void showLoginWindow() {
	Intent intent = new Intent();
	intent.setClass(getActivity(), LoginActivity.class);
	startActivityForResult(intent, 0);
    }

    // 设置条目点击的监听事件
    private class onSelectionItemClick implements OnClickListener {
	// 点击事件对应的内容的集合
	private Map<String, String> who;
	private Button button;

	public onSelectionItemClick(Map<String, String> who, Button button) {
	    this.who = who;
	    this.button = button;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
	    // 选择条目后的动作
	    button.setText(map2Array(who)[which]);
	    if (who == kbSelection.getDepts()) {
		getClasses();
	    }
	}

    }

    private void getSelection() {
	Message msg = myHandler.obtainMessage();
	msg.what = SHOWPROGRESSDIALOG;
	msg.getData().putString("msg", "请稍候...");
	myHandler.sendMessage(msg);
	StudentServiceImpl.getInstance().queryKbSelection(new BusinessHttpCallBack() {
	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		Message msg = myHandler.obtainMessage();
		msg.what = LOADINGFAILED;
		msg.getData().putString("msg", failuremsg);
		myHandler.sendMessage(msg);
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
		kbSelection = (KbSelection) obj;
		myHandler.sendEmptyMessage(LOADINGSELECTIONFINISHED);
	    }

	});
    }

    private void getClasses() {
	Message msg = myHandler.obtainMessage();
	msg.what = SHOWPROGRESSDIALOG;
	msg.getData().putString("msg", "正在查找班级...");
	myHandler.sendMessage(msg);
	String sYear = kbSelection.getYears().get(bt_year.getText().toString());
	String sTerms = kbSelection.getTerms().get(bt_term.getText().toString());
	String sDept = kbSelection.getDepts().get(bt_dept.getText().toString());
	String sClasses = kbSelection.getClasses().get(bt_class.getText().toString());
	StudentServiceImpl.getInstance().queryClass(sYear, sTerms, sDept, sClasses, new BusinessHttpCallBack() {

	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		Message msg = myHandler.obtainMessage();
		msg.what = LOADINGFAILED;
		msg.getData().putString("msg", failuremsg);
		myHandler.sendMessage(msg);
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
		currentClass = (Map<String, String>) obj;
		myHandler.sendEmptyMessage(LOADIINGCLASSFINISHED);
	    }

	});
    }

    private void getTimeTable() {
	Message msg = myHandler.obtainMessage();
	msg.what = SHOWPROGRESSDIALOG;
	msg.getData().putString("msg", "正在查询课表...");
	myHandler.sendMessage(msg);
	String sYear = kbSelection.getYears().get(bt_year.getText().toString());
	String sTerms = kbSelection.getTerms().get(bt_term.getText().toString());
	String sDept = kbSelection.getDepts().get(bt_dept.getText().toString());
	String sClasses = kbSelection.getClasses().get(bt_class.getText().toString());
	StudentServiceImpl.getInstance().queryKebiao(sYear, sTerms, sDept, sClasses, new BusinessHttpCallBack() {
	    @Override
	    public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
		Message msg = myHandler.obtainMessage();
		msg.what = LOADINGFAILED;
		msg.getData().putString("msg", failuremsg);
		myHandler.sendMessage(msg);
	    }

	    @Override
	    public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
		timetable = (String[][]) obj;
		myHandler.sendEmptyMessage(LOADINGTIMETABLEFINISHED);
	    }

	});
    }
}
